//
//  HomeBaseViewController.m
//  Fireball
//
//  Created by 俞渊华 on 2017/12/4.
//  Copyright © 2017年 俞渊华. All rights reserved.
//

#import "HomeBaseViewController.h"
#import "HomeBaseCell.h"
#import "HomeOneImageCell.h"
#import "NewsMoreImageCell.h"
#import "NewsVideoCell.h"
#import "AticleModel.h"
#import "NewsDetailViewController.h"///普通新闻详情页
#import "VideoDetailViewController.h"///视频详情页
#import "WMPlayer.h"
#import "UserSites.h"
#import "WorkOrderModel.h"
#import "HomeViewController.h"
#import "MenuTool.h"
#import "MenuRole.h"
#import "RouteViewController.h"
#import "ChangeShiftViewController.h"
#import "SpotTaskViewController.h"
#import "AuditViewController.h"
#import "WorkOrderModelCopy.h"
#import "MMZCViewController.h"
#import "PointModel.h"

@interface HomeBaseViewController ()<UITableViewDelegate,UITableViewDataSource,HomeSortDelegate>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *aticleArray;
@property(nonatomic, strong)NSMutableArray *countArray;

@property (nonatomic,strong) WMPlayer *wmPlayer; // 播放器View

@property(nonatomic, assign)NSInteger pageSize;
@property(nonatomic, assign)NSInteger pageIndex;
@property(nonatomic, assign)BOOL sort;

@end

@implementation HomeBaseViewController
static HomeBaseViewController *hbvc = nil;

+ (instancetype)share {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        hbvc = [[self alloc] init];
    });
    return hbvc;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageSize = 20;
    self.pageIndex = 1;
    self.aticleArray = [NSMutableArray array];
    self.countArray = [NSMutableArray array];

    [self.view addSubview:self.tableView];
    self.sort=NO;
    /** MJRefresh的block也需要用若引用 */
    WEAKSELF
    self.tableView.mj_header = [XMRefreshHeader xm_headerWithRefreshingBlock:^{
        if (![MySingleton sharedMySingleton].network) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:@"请检查网络状态" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return;
        }
        self.pageIndex = 1;
//        [self.aticleArray removeAllObjects];
        if (_menu.menuId==-1) {
        [self postUIinfo];
            [MySingleton sharedMySingleton].finished=NO;
        }
        else
        {
            [MySingleton sharedMySingleton].finished=YES;
            [self postFinishUI];
        }
//        [weakSelf searchAticle];
        if (![[UserInfo share].role.powerType isEqualToString:@"1"]) {
            [self postFinishCountUI];
        }
    }];
    //默认block方法：设置上拉加载更多
    if (![MySingleton sharedMySingleton].finished) {
    self.tableView.mj_footer = [XMRefreshFooter xm_footerWithRefreshingBlock:^{
        self.pageIndex += 1;
        [self.tableView.mj_footer endRefreshing];
//        [weakSelf searchAticle];
    }];
    }
//    [self.tableView.mj_header beginRefreshing];
    
    
    //旋转屏幕通知
    [XMNotificationCenter addObserver:self
                             selector:@selector(onDeviceOrientationChange)
                                 name:UIDeviceOrientationDidChangeNotification
                               object:nil];
    //为一个特定的通知添加监听者
    //刷新token后跳转刷新的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(noti:) name:@"noti" object:nil];
}
-(void)setMenu:(AticleMenu *)menu{
    _menu = menu;
    if (menu.menuId==-1) {
        [MySingleton sharedMySingleton].finished=NO;
    [self.tableView.mj_header beginRefreshing];
    }
    else
    {
        [MySingleton sharedMySingleton].finished=YES;
        [self postFinishUI];//已完成任务入口
    }
}
- (void)onDeviceOrientationChange{
    NSLog(@"onDeviceOrientationChange");
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(-55);
        //不知原因用edges下面对不齐
//        make.edges.mas_equalTo(self.view);
    }];
}
-(void)syncSuccess
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView.mj_header beginRefreshing];
    });
}
#pragma mark -
#pragma mark SlideSegmentDelegate
//任务排序
- (void)homeDidSelectedAtIndex:(NSInteger)index {
//    if (index == _selectedIndex) {return;}
//    [self switchToIndex:index];
    if (_sort) {
        if (index==1) {
            NSArray *sortArray = [self.aticleArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                
                WorkOrderModel *pModel1 = obj1;
                WorkOrderModel *pModel2 = obj2;
                if (pModel1.priority > pModel2.priority) { //不使用intValue比较无效
                    return NSOrderedDescending;//降序
                }else if (pModel1.priority < pModel2.priority){
                    return NSOrderedAscending;//升序
                }else {
                    return NSOrderedSame;//相等
                }
                
            }];
            [self.aticleArray removeAllObjects];
            self.aticleArray=[NSMutableArray arrayWithArray:sortArray];
            [self.tableView reloadData];
        }
        else if (index==2)
        {
            NSArray *sortArray = [self.aticleArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                
                WorkOrderModel *pModel1 = obj1;
                WorkOrderModel *pModel2 = obj2;
                if ([pModel1.proposalStartTime doubleValue] > [pModel2.proposalStartTime doubleValue]) { //不使用intValue比较无效
                    return NSOrderedDescending;//降序
                }else if ([pModel1.proposalStartTime doubleValue] < [pModel2.proposalStartTime doubleValue]){
                    return NSOrderedAscending;//升序
                }else {
                    return NSOrderedSame;//相等
                }
                
            }];
            [self.aticleArray removeAllObjects];
            self.aticleArray=[NSMutableArray arrayWithArray:sortArray];
            [self.tableView reloadData];
            
        }
        else if (index==3)
        {
            NSArray *sortArray = [self.aticleArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                
                WorkOrderModel *pModel1 = obj1;
                WorkOrderModel *pModel2 = obj2;
                if (pModel1.state < pModel2.state) { //不使用intValue比较无效
                    return NSOrderedDescending;//降序
                }else if (pModel1.state > pModel2.state){
                    return NSOrderedAscending;//升序
                }else {
                    return NSOrderedSame;//相等
                }
                
            }];
            [self.aticleArray removeAllObjects];
            self.aticleArray=[NSMutableArray arrayWithArray:sortArray];
            [self.tableView reloadData];
        }
    }
    else
    {
    if (index==1) {
    NSArray *sortArray = [self.aticleArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
        WorkOrderModel *pModel1 = obj1;
        WorkOrderModel *pModel2 = obj2;
        if (pModel1.priority < pModel2.priority) { //不使用intValue比较无效
            return NSOrderedDescending;//降序
        }else if (pModel1.priority > pModel2.priority){
            return NSOrderedAscending;//升序
        }else {
            return NSOrderedSame;//相等
        }
        
    }];
    [self.aticleArray removeAllObjects];
    self.aticleArray=[NSMutableArray arrayWithArray:sortArray];
    [self.tableView reloadData];
    }
    else if (index==2)
    {
        NSArray *sortArray = [self.aticleArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            
            WorkOrderModel *pModel1 = obj1;
            WorkOrderModel *pModel2 = obj2;
            if ([pModel1.proposalStartTime doubleValue] < [pModel2.proposalStartTime doubleValue]) { //不使用intValue比较无效
                return NSOrderedDescending;//降序
            }else if ([pModel1.proposalStartTime doubleValue] > [pModel2.proposalStartTime doubleValue]){
                return NSOrderedAscending;//升序
            }else {
                return NSOrderedSame;//相等
            }
            
        }];
        [self.aticleArray removeAllObjects];
        self.aticleArray=[NSMutableArray arrayWithArray:sortArray];
        [self.tableView reloadData];
        
    }
    else if (index==3)
    {
        NSArray *sortArray = [self.aticleArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            
            WorkOrderModel *pModel1 = obj1;
            WorkOrderModel *pModel2 = obj2;
            if (pModel1.state > pModel2.state) { //不使用intValue比较无效
                return NSOrderedDescending;//降序
            }else if (pModel1.state < pModel2.state){
                return NSOrderedAscending;//升序
            }else {
                return NSOrderedSame;//相等
            }
            
        }];
        [self.aticleArray removeAllObjects];
        self.aticleArray=[NSMutableArray arrayWithArray:sortArray];
        [self.tableView reloadData];
    }
    }
    self.sort=!self.sort;
}
//已完成任务查询本地数据库
-(void)postFinishUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    NSDateFormatter *isoFormat = [[NSDateFormatter alloc] init];
    [isoFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
    NSDate *currentDate = [NSDate date]; // GMT

    NSInteger dis = 3; //前后的天数,保安队长只能3天内的已完成工单
    
    NSDate*nowDate = [NSDate date];
    NSDate* theDate;
    
    if(dis!=0)
    {
        NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
        
        theDate = [nowDate initWithTimeIntervalSinceNow: +oneDay*dis ];
        //or
        theDate = [nowDate initWithTimeIntervalSinceNow: -oneDay*dis ];
    }
    else
    {
        theDate = nowDate;
    }
    
//    NSArray * array = [WorkOrderModel findWhere:@[@"executeState",@"=",@(1)]];
//    [self.aticleArray removeAllObjects];
//    [self.aticleArray addObjectsFromArray:array];
//    [self.tableView reloadData];
//    if (self.blockFinish) {
//        self.blockFinish(_aticleArray.count,0);
//    }
    NSDictionary *params = @{
                             //                             @"siteUuid" : s.uuid,
                             @"startDate" : [isoFormat stringFromDate:theDate]
                             };
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool post:@"digiops/app/workOrder/SelectCompletedList" params:params success:^(id responseObj) {
        if (responseObj[@"content"]==[NSNull null]) {
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
            return;
        }
        [self.aticleArray removeAllObjects];

        for (NSDictionary* order in responseObj[@"content"]) {
            WorkOrderModel* o=[WorkOrderModel mj_objectWithKeyValues:order];
            o.ViewType=2;//为了兼容viewtype
            [self.aticleArray addObject:o];
            //保存数据库
//            [o saveOrUpdateAsync:^(BOOL isSuccess) {
//                NSLog(@"");
//
//            }];
            NSLog(@"");
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        if (self.blockFinish) {
                self.blockFinish(_aticleArray.count,0);
            }
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

-(NSString *)getNDay:(NSInteger)n{
    
    NSDate*nowDate = [NSDate date];
    
    NSDate* theDate;
    
    if(n!=0){
        
        NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
        theDate = [nowDate initWithTimeIntervalSinceNow: oneDay*n ];//initWithTimeIntervalSinceNow是从现在往前后推的秒数
        
    }else{
        
        theDate = nowDate;
    }
    
    NSDateFormatter *date_formatter = [[NSDateFormatter alloc] init];
    [date_formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *the_date_str = [date_formatter stringFromDate:theDate];
    
    return the_date_str;
}

//获取用户信息
-(void)postUIinfo{
    NSDictionary *params = @{
                             @"access_token" : [MySingleton sharedMySingleton].tokenID
                             };
    //    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool get:@"digiops/app/user/getUsers" params:params success:^(id responseObj) {
        NSLog(@"");
        if (responseObj[@"result"]==[NSNull null]) {
            return;
        }
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //角色
        UserRole* role=[UserRole mj_objectWithKeyValues:responseObj[@"result"][@"role"]];

        //用户
        UserInfo* user=[UserInfo mj_objectWithKeyValues:responseObj[@"result"]];
        //user share
        [UserInfo share].userNum=user.userNum;
        [UserInfo share].userName=user.userName;
        [UserInfo share].passWord=user.passWord;
        //权限
        NSArray* b=[user.role.menuRoleDTOs objectAtIndex:1];//权限取的临时任务
        MenuRole* m=[MenuRole mj_objectWithKeyValues:b];
        role.powerType=m.powerType;
        [UserInfo share].role=role;
        [UserInfo share].roleName=user.roleName;
        [UserInfo share].telephone=user.telephone;
        [UserInfo share].sites=user.sites;
        [UserInfo share].uuid=user.uuid;
        //
        [self postUI];
        //站点
        //        for (NSDictionary* site in self.user.sites) {
        //            UserSites* s=[UserSites mj_objectWithKeyValues:site];
        //            NSLog(@"");
        //        }
        NSLog(@"");
        //        rootViewController = nav;
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        [self.tableView.mj_header endRefreshing];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        
    }];
}
-(void)searchAticle{
    NSDictionary * dict = @{@"MenuType":@(self.menu.menuId),
                            @"PageInfo":@{@"CurrentPage":@(self.pageIndex),
                                          @"PageSize":@(self.pageSize)
                                          },
                            @"StrKey":@"",
                            @"iType":@"0"
                            };
    [FBNetworkTool get:@"articleapi/com.SearchAticle" parameters:dict showHUD:NO responseCache:^(XMHttpResponseModel *responseModel) {
        NSArray * array = [AticleModel mj_objectArrayWithKeyValuesArray:responseModel.data];
        [self.aticleArray addObjectsFromArray:array];
        [self.tableView reloadData];
        
    } success:^(XMHttpResponseModel *responseModel) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        NSArray * array = [AticleModel mj_objectArrayWithKeyValuesArray:responseModel.data];
        [self.aticleArray addObjectsFromArray:array];
        if (array.count == 0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    }];

}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.aticleArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    AticleModel * model = self.aticleArray[indexPath.row];
    WorkOrderModel* model=self.aticleArray[indexPath.row];
    if (model.ViewType == 1) {
        HomeBaseCell * cell = [HomeBaseCell cellWithTableView:tableView];
//        cell.model = model;
        return cell;
    }else if (model.ViewType == 2) {
        HomeOneImageCell *cell = [HomeOneImageCell cellWithTableView:tableView];
        //测试数据
        model.orderid=indexPath.row;
        //查数据库执行状态
//        NSArray* array=[WorkOrderModel findWhere:@[@"uuid",@"=",model.uuid]];
//        if (array.count>0) {
//            WorkOrderModel* d=(WorkOrderModel*)array[0];
//        model.executeState=d.executeState;
//        }
        cell.model = model;
        cell.block = ^(NSString *orderId, NSArray *lines) {
        
            for (WorkOrderModel* wom in self.aticleArray) {
                if ([wom.uuid isEqualToString:orderId]) {
                    wom.lines=lines;
                    if ([MySingleton sharedMySingleton].reject)
                        wom.executeState=[@"2" integerValue];//应该是拒绝
                    else
                        wom.executeState=[@"1" integerValue];//应该是待提交
                    WorkOrderModelCopy* womc=[WorkOrderModelCopy new];
                    womc.uuid=wom.uuid;
                    womc.executeState=wom.executeState;
                    womc.workOrderNum=wom.workOrderNum;
                    //任务显示不正常标识
                    for (LineDetail* ld in lines) {
                        for (PointModel* pm in ld.soprouteArray) {
                            if ([pm.content isEqualToString:@"不正常"]) {
                                wom.isAbnormal=@"1";
                                womc.isAbnormal=@"1";
                                break;
                            }
                        }
                        //异常备注显示不正常标识
                        if ([ld.exceptionState isEqualToString:@"1"]) {
                            if (!ld.scaned) {//扫描过的不
                            wom.isAbnormal=@"1";
                            womc.isAbnormal=@"1";
                            }
                            break;
                        }
                    }
                    [womc saveOrUpdateAsync:^(BOOL isSuccess) {//存工单状态
                        NSLog(@"");
                    }];
                }
                [wom saveOrUpdateAsync:^(BOOL isSuccess) {
                }];
            }
            [RouteViewController share].orderCopy=self.aticleArray;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        };
        cell.blockShift = ^(NSString *orderId, NSArray *lines) {
            for (WorkOrderModel* wom in self.aticleArray) {
                if ([wom.uuid isEqualToString:orderId]) {
                    wom.lines=lines;
                    if ([MySingleton sharedMySingleton].reject)
                        wom.executeState=[@"2" integerValue];//应该是拒绝
                    else{
                    if (wom.executeState==0||wom.executeState==3)
                        wom.executeState=[@"1" integerValue];//应该是待提交
                    }
                    WorkOrderModelCopy* womc=[WorkOrderModelCopy new];
                    womc.uuid=wom.uuid;
                    womc.executeState=wom.executeState;
                    womc.workOrderNum=wom.workOrderNum;
                    //任务显示不正常标识
                        for (PointModel* pm in lines) {
                            if ([pm.content isEqualToString:@"不正常"]) {
                                wom.isAbnormal=@"1";
                                womc.isAbnormal=@"1";
                                break;
                            }
                        }
                    
                    [womc saveOrUpdateAsync:^(BOOL isSuccess) {//存工单状态
                        NSLog(@"");
                    }];
                    NSLog(@"");
                }
                [wom saveOrUpdateAsync:^(BOOL isSuccess) {
                }];
            }
            [ChangeShiftViewController share].orderCopy=self.aticleArray;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.tableView reloadData];
                    });
        };
        cell.blockSpot = ^(WorkOrderModel* m) {
            
            for (WorkOrderModel* wom in self.aticleArray) {
                if ([wom.uuid isEqualToString:m.uuid]) {
                    wom.spotCommnet=m.spotCommnet;
                    wom.spotPicture=m.spotPicture;
                    wom.refuseRemark=m.refuseRemark;//备注混淆问题
                    if ([MySingleton sharedMySingleton].reject){
                        wom.executeState=[@"2" integerValue];//应该是拒绝
                        wom.rejectCount=m.rejectCount;//拒绝次数要赋值再回去，再同步
                    }
                    else{
                    if (wom.executeState==0||wom.executeState==2)
                        wom.executeState=[@"1" integerValue];//应该是待提交
                    }
                    WorkOrderModelCopy* womc=[WorkOrderModelCopy new];
                    womc.uuid=wom.uuid;
                    womc.executeState=wom.executeState;
                    womc.workOrderNum=wom.workOrderNum;
                    [womc saveOrUpdateAsync:^(BOOL isSuccess) {//存工单状态
                        NSLog(@"");
                    }];
                }
                [wom saveOrUpdateAsync:^(BOOL isSuccess) {
                }];
            }
            [SpotTaskViewController share].orderCopy=self.aticleArray;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        };
        cell.blockAudit = ^(NSString *orderId, NSArray *lines) {
            
            for (WorkOrderModel* wom in self.aticleArray) {
                if ([wom.uuid isEqualToString:orderId]) {
                    wom.lines=lines;
                    if ([MySingleton sharedMySingleton].reject)
                        wom.executeState=[@"2" integerValue];//应该是拒绝
                    else{
                    wom.executeState=[@"1" integerValue];//应该是待提交
                    }
                    WorkOrderModelCopy* womc=[WorkOrderModelCopy new];
                    womc.uuid=wom.uuid;
                    womc.executeState=wom.executeState;
                    womc.workOrderNum=wom.workOrderNum;
                    [womc saveOrUpdateAsync:^(BOOL isSuccess) {//存工单状态
                        NSLog(@"");
                    }];
                }
                [wom saveOrUpdateAsync:^(BOOL isSuccess) {
                }];
            }
            [AuditViewController share].orderCopy=self.aticleArray;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        };
        cell.blockReject = ^{
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];

            NSArray *indexArray=[NSArray arrayWithObject:indexPath];
            [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:NO];
//            [self.tableView reloadData];
            
//            [self.tableView.mj_header beginRefreshing];
        };
        cell.blockRejectSpot = ^{
            
            [self.tableView.mj_header beginRefreshing];
        };
        return cell;
    }else if (model.ViewType == 3){
        NewsMoreImageCell * cell = [NewsMoreImageCell cellWithTableView:tableView];
//        cell.model = model;
        return cell;
    }else if (model.ViewType == 4){
        HomeOneImageCell *cell = [HomeOneImageCell cellWithTableView:tableView];
        cell.model = model;
        return cell;
//        NewsVideoCell * cell = [NewsVideoCell cellWithTableView:tableView];
////        cell.model = model;
//        return cell;
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    AticleModel * model = self.aticleArray[indexPath.row];
    if (model.ViewType == 1) {
        return [HomeBaseCell heightWithModel:model];
        
    }else if (model.ViewType == 2) {
        return [HomeOneImageCell heightWithModel:model];
        
    }else if (model.ViewType == 3){
        return [NewsMoreImageCell heightWithModel:model];
    }else if (model.ViewType == 4){
        return [HomeOneImageCell heightWithModel:model];
    }
    return 100;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
    NewsDetailViewController * detailVC = [[NewsDetailViewController alloc]init];
    detailVC.model = self.aticleArray[indexPath.row];
    [self.rt_navigationController pushViewController:detailVC animated:YES];
     */
}


- (UITableView *)tableView{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = [UIView new];
        _tableView = tableView;
    }
    return _tableView;
}
-(void)noti:(NSNotification *)noti{
    NSLog(@"%@",noti.userInfo);
    [self syncSuccess];
}
-(void)postUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    NSDateFormatter *isoFormat = [[NSDateFormatter alloc] init];
    [isoFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
    NSDate *currentDate = [NSDate date]; // GMT
    
    NSInteger dis = 30; //前后的天数
    
    NSDate*nowDate = [NSDate date];
    NSDate* theDate;
    
    if(dis!=0)
    {
        NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
        
        theDate = [nowDate initWithTimeIntervalSinceNow: +oneDay*dis ];
        //or
        theDate = [nowDate initWithTimeIntervalSinceNow: -oneDay*dis ];
    }
    else
    {
        theDate = nowDate;
    }
    
    //增量时间
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDate* password = [defaults objectForKey:@"updatetime"];
    if (password) {
        NSTimeInterval timeInterval = [password timeIntervalSince1970];
        NSTimeInterval timeInterval1 = [nowDate timeIntervalSince1970];
        NSTimeInterval xx=timeInterval1-timeInterval;
        theDate=[nowDate initWithTimeIntervalSinceNow: -(timeInterval1-timeInterval)];
    }
    //
    //时区问题多8小时问题
    NSDateFormatter *isoFormat1 = [[NSDateFormatter alloc] init];
    [isoFormat1 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
    
    NSString *timeString = @"Sun Sep 13 11:43:04 +0800 2015";
    
    NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    
    format.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
    
    format.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    
    format.timeZone = sourceTimeZone;
    
    NSDate *date = [format dateFromString:[isoFormat1 stringFromDate:theDate]];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localDate = [date dateByAddingTimeInterval:-interval];//减掉8小时，代码不得不这么写了
    
    NSLog (@"date: %@", localDate );
    
    
    //原来时间代码
    NSDateFormatter *aisoFormat = [[NSDateFormatter alloc] init];
    [aisoFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
    
    
    ////
    NSDictionary *params = @{
                             //                             @"siteUuid" : s.uuid,
                             @"startTime" : [aisoFormat stringFromDate:localDate]
                             };
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool post:@"digiops/app/workOrder/SelectWorkOrderList" params:params success:^(id responseObj) {
        NSLog(@"");
        [self.aticleArray removeAllObjects];
        if (![responseObj[@"message"] isEqualToString:@"服务端异常"]) {
            
            //增量时间
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            NSDate* password = [defaults objectForKey:@"updatetime"];
            if (password) {
                NSArray* array=[WorkOrderModel findAll];
                
                self.aticleArray=[array mutableCopy];
                NSArray *sortArray = [self.aticleArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                    
                    WorkOrderModel *pModel1 = obj1;
                    WorkOrderModel *pModel2 = obj2;
                    if ([pModel1.proposalStartTime doubleValue] < [pModel2.proposalStartTime doubleValue]) { //不使用intValue比较无效
                        return NSOrderedDescending;//降序
                    }else if ([pModel1.proposalStartTime doubleValue] > [pModel2.proposalStartTime doubleValue]){
                        return NSOrderedAscending;//升序
                    }else {
                        return NSOrderedSame;//相等
                    }
                    
                }];
                //记住状态
                for (WorkOrderModel* o in sortArray ) {
                    o.ViewType=2;//为了兼容viewtype
                    //查数据库执行状态
                    NSArray* array=[WorkOrderModelCopy findWhere:@[@"uuid",@"=",o.uuid]];
                    if (array.count>0) {
                        WorkOrderModelCopy* d=(WorkOrderModelCopy*)array[0];
                        o.executeState=d.executeState;
                        o.isAbnormal=d.isAbnormal;
                    }
                }
                [self.aticleArray removeAllObjects];
                self.aticleArray=[NSMutableArray arrayWithArray:sortArray];
            }
            
            for (NSDictionary* order in responseObj[@"content"]) {
                WorkOrderModel* o=[WorkOrderModel mj_objectWithKeyValues:order];
                o.ViewType=2;//为了兼容viewtype
                //查数据库执行状态
                NSArray* array=[WorkOrderModelCopy findWhere:@[@"uuid",@"=",o.uuid]];
                if (array.count>0) {
                    WorkOrderModelCopy* d=(WorkOrderModelCopy*)array[0];
                    o.executeState=d.executeState;
                    o.isAbnormal=d.isAbnormal;
                }
                
                //失效工单状态
                if (o.state==0) {
                    if (!password) {//已完成工单在第一次的时候不存数据库，CR没有这个问题
                        if (o.executeState != 1) {
                            [self.aticleArray addObject:o];
                        }
                    }
                    else
                        [self.aticleArray addObject:o];
                    [o saveOrUpdate];
                }
//                [self.aticleArray addObject:o];
                
                
                NSLog(@"");
            }
            //去除失效工单，分开进行因为上面存数据库可能未完成
            for (NSDictionary* order in responseObj[@"content"]) {
                WorkOrderModel* o=[WorkOrderModel mj_objectWithKeyValues:order];

                if(o.state==1)
                {
                    [WorkOrderModel deleteWhere:@[@"uuid",@"=",o.uuid]];
                    //                    [self postUI];
                    NSMutableArray* sopTemp=[NSMutableArray new];
                    for (WorkOrderModel* om in self.aticleArray) {
                        if ([om.uuid isEqualToString:o.uuid]) {
                        }
                        else{
                            [sopTemp addObject:om];
                        }
                    }
                    [self.aticleArray removeAllObjects];
                    self.aticleArray=sopTemp;
                }
                //                [self.aticleArray addObject:o];
                
                
                NSLog(@"");
            }
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setObject:nowDate forKey:@"updatetime"];
            [userDefault synchronize];
        }
        [self.tableView reloadData];
        if (self.block) {
            self.block(_aticleArray.count,0);
        }
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
//        static dispatch_once_t onceToken;
//        dispatch_once(&onceToken, ^{
//        [[MMZCViewController share] offline];//调用离线接口，获取全部数据
//        });
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        NSString* err=[error localizedDescription];
        if ([err containsString:@"refreshtoken"]) {
            [self syncSuccess];
        }
    }];
}
//就取未完成工单计数
-(void)postFinishCountUI{
    UserSites* s=[UserSites mj_objectWithKeyValues:[UserInfo share].sites[0]];
    NSDateFormatter *isoFormat = [[NSDateFormatter alloc] init];
    [isoFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
    NSDate *currentDate = [NSDate date]; // GMT
    
    NSInteger dis = 3; //前后的天数
    
    NSDate*nowDate = [NSDate date];
    NSDate* theDate;
    
    if(dis!=0)
    {
        NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
        
        theDate = [nowDate initWithTimeIntervalSinceNow: +oneDay*dis ];
        //or
        theDate = [nowDate initWithTimeIntervalSinceNow: -oneDay*dis ];
    }
    else
    {
        theDate = nowDate;
    }
    
    //    NSArray * array = [WorkOrderModel findWhere:@[@"executeState",@"=",@(1)]];
    //    [self.aticleArray removeAllObjects];
    //    [self.aticleArray addObjectsFromArray:array];
    //    [self.tableView reloadData];
    //    if (self.blockFinish) {
    //        self.blockFinish(_aticleArray.count,0);
    //    }
    NSDictionary *params = @{
                             //                             @"siteUuid" : s.uuid,
                             @"startDate" : [isoFormat stringFromDate:theDate]
                             };
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    [HttpTool post:@"digiops/app/workOrder/SelectCompletedList" params:params success:^(id responseObj) {
        if (responseObj[@"content"]==[NSNull null]) {
            [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
            [self.tableView.mj_header endRefreshing];
            return;
        }
        [self.countArray removeAllObjects];
        
        for (NSDictionary* order in responseObj[@"content"]) {
            WorkOrderModel* o=[WorkOrderModel mj_objectWithKeyValues:order];
            o.ViewType=2;//为了兼容viewtype
            [self.countArray addObject:o];
            //保存数据库
            //            [o saveOrUpdateAsync:^(BOOL isSuccess) {
            //                NSLog(@"");
            //
            //            }];
            NSLog(@"");
        }

        if (self.blockFinish) {
            self.blockFinish(_countArray.count,0);
        }
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];
        [self.tableView.mj_header endRefreshing];
        //        [UITool showMBProgressHud:[UIApplication sharedApplication].keyWindow withText:@"登录失败，稍后再试" withTime:1.0];
        
        //        [MBProgressHUD hideAllHUDsForView:[UIApplication sharedApplication].keyWindow animated:YES];

    }];
}
@end
